import 'package:sqflite_common_ffi/sqflite_ffi.dart';

import '../core/engine.dart';

class Cache {
  String key;
  String value;
  Cache({required this.key, required this.value});
}

class CacheDao {
  final SqilteEngine _sqilteEngine = SqilteEngine();
  Database? _database;
  String tableName = "cache";
  CacheDao() {
    _initDatabse();
  }
  // 初始化数据库连接
  Future _initDatabse() async {
    _database = await _sqilteEngine.initMessageDatabase();
    return _database;
  }

  // 查询数据
  Future getData(String key) async {
    return await _queryData(key);
  }

  // 插入数据
  Future setData(String key, String value) async {
    List<Cache>? data = await _queryData(key);
    if (data.isNotEmpty) {
      return await _updateData(key, value);
    }
    return await _insertData(key, value);
  }

  // 插入数据
  Future _insertData(String key, String value) async {
    _database = await _initDatabse();
    return await _database?.insert(tableName, {key: value});
  }

  Future _updateData(String key, String value) async {
    _database = await _initDatabse();
    return await _database?.update(tableName, {key: value});
  }

  Future<List<Cache>> _queryData(String key) async {
    _database = await _initDatabse();
    List<Map<String, dynamic>>? maps =
        await _database?.query(tableName, where: "key = ?", whereArgs: [key]);
    return List.generate(maps!.length, (index) {
      return Cache(key: key, value: maps[index][key]);
    });
  }
}
